//
//  PhotoDetailViewController.m
//  Brand
//
//  Created by Woody Yan on 5/7/14.
//  Copyright (c) 2014 Faker. All rights reserved.
//

#import "config.h"
#import "Photo.h"
#import "AFGetData.h"
#import "PhotoDetailViewController.h"
#import "UIImageView+WebCache.h" //SDWebImage
#import "HMSegmentedControl.h"
#import <Frontia/Frontia.h>
#import "CollectionFixedHeaderLayout.h"
#import "Header.h"

#define CellIdentifer      @"CellIdentifer"

@interface PhotoDetailViewController ()

@property (strong,nonatomic) UIImageView *imageView;
@property (strong,nonatomic) HMSegmentedControl *segmentedControl;
@property (strong,nonatomic) UIImageView *coverImageView;

@property (strong, nonatomic) UICollectionView* myCollectionView;
@property (strong, nonatomic) Photo* currentPhoto;


@end

@implementation PhotoDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
   UIImage *background = [UIImage imageNamed:@"Layer.png"];
	self.view.backgroundColor = [UIColor colorWithPatternImage:background];
    
    [self setUp];
    
    self.segmentedControl = [[HMSegmentedControl alloc] initWithSectionImages:@[
                                                 [UIImage imageNamed:@"photoDetail_return.png"],
                                                 [UIImage imageNamed:@"photoDetail_preview.png"],
                                                 [UIImage imageNamed:@"photoDetail_download.png"],
                                                 [UIImage imageNamed:@"photoDetail_share.png"]]
                                                        sectionSelectedImages: nil];
    self.segmentedControl.frame = CGRectMake(0,kScreen_Height - 49 , kScreen_Width, 49);
    self.segmentedControl.backgroundColor = RGBA(0, 0, 0, .5);
    self.segmentedControl.selectedSegmentIndex = HMSegmentedControlNoSegment;
    self.segmentedControl.selectionIndicatorHeight = 0.0f;
    self.segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleBox;
    self.segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationUp;
    [self.segmentedControl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segmentedControl];
}


-(void)setUp
{
    
    CGRect frame = CGRectMake(0, 0, kScreen_Width, kScreen_Height);
    self.myCollectionView = [self drawCollectionViewWithFrame:frame andFlowLayout:[self getFlowLayout]];
    [self registerCellAndHeaderForCollectionView:self.myCollectionView];
    self.myCollectionView.contentOffsetLeft = self.view.width*self.currentItemIndex;
    [self.view addSubview:self.myCollectionView];
    
}

#pragma mark - CollectionView methods
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataArray.count;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier =CellIdentifer;
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    
    Photo* photo = [self.dataArray objectAtIndex:indexPath.row];
    __weak Photo* weakPhoto = photo;
    UIImageView* mImageView = (UIImageView*)[cell viewWithTag:302];
    
    if([photo.type isEqualToString:@"1"])
    {
        if([[UserObj sharedInstance] isLegalVip])
        {
            [mImageView setImageWithURL:[NSURL URLWithString:photo.largeUrl]
                       placeholderImage:photo.thumbnail
                              completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType){
                                  if (!error) {
                                      weakPhoto.largeImage = image;
                                  }
                              }];

        }
        else{
            [mImageView setImageWithURL:[NSURL URLWithString:photo.thumbUrl]
                       placeholderImage:photo.thumbnail
                              completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType){
                                  if (!error) {
                                      weakPhoto.largeImage = photo.thumbnail; //就让他下一个缩略图
                                  }
                              }];

        
        }
    }
    else{
        
        [mImageView setImageWithURL:[NSURL URLWithString:photo.largeUrl]
                   placeholderImage:photo.thumbnail
                          completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType){
                              if (!error) {
                                  weakPhoto.largeImage = image;
                              }
                          }];

    }
    
    
    
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    self.segmentedControl.hidden = !self.segmentedControl.hidden;
    if(self.coverImageView.hidden == NO)
    {
        self.coverImageView.hidden = YES;
    }
}


#pragma mark - UIScrollView methods
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    float offX = scrollView.contentOffsetLeft;
    int index = floorf(offX/self.view.width);
    
    if(index<0)
    {
        index = 0;
    }
    if(index>=self.dataArray.count)
    {
        index = self.dataArray.count - 1;
    }
    self.currentItemIndex = index;
    
}

#pragma mark - 生成collectionview和布局布局管理器
-(UICollectionView*)drawCollectionViewWithFrame:(CGRect)frame andFlowLayout:(CollectionFixedHeaderLayout*)flowLayout
{
    UICollectionView* myCollectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
    
    myCollectionView.showsVerticalScrollIndicator = NO;
    myCollectionView.showsHorizontalScrollIndicator = NO;
    myCollectionView.dataSource = self;
    myCollectionView.delegate = self;
    myCollectionView.pagingEnabled = YES;
    myCollectionView.backgroundColor = [UIColor clearColor];
    
    return myCollectionView;
}

-(void)registerCellAndHeaderForCollectionView:(UICollectionView*)collectionView {
    UINib *cellNib = nil;
    cellNib = [UINib nibWithNibName:@"PhotoCell" bundle:nil];
    [collectionView registerNib:cellNib forCellWithReuseIdentifier:CellIdentifer];
    
}

//一个布局管理器只能对应一个collectionView
-(CollectionFixedHeaderLayout*)getFlowLayout
{
    CollectionFixedHeaderLayout *flowLayout = [[CollectionFixedHeaderLayout alloc] init];
    flowLayout.isFiexed = NO;
    [flowLayout setItemSize:CGSizeMake(kScreen_Width, kScreen_Height)];
    flowLayout.minimumInteritemSpacing =0;
    flowLayout.minimumLineSpacing = 0;
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    return flowLayout;
}


-(void)viewWillLayoutSubviews{
     self.view.frame = CGRectMake(0, 0, kScreen_Width, kScreen_Height);
}

- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
    
}

- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
}


- (void) viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   
	[self.view.subviews enumerateObjectsUsingBlock:^(UIView* obj, NSUInteger idx, BOOL *stop) {
		if ([obj isKindOfClass:[UIImageView class]] && obj == self.coverImageView) {
                self.segmentedControl.hidden = NO;
		}
	}];
}


#pragma mark - Segment Control

- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl
{
    self.coverImageView.hidden = YES;
    
    switch (self.segmentedControl.selectedSegmentIndex)
    {
        case 0: {
            //[self.navigationController popViewControllerAnimated:YES];
            [self dismissViewControllerAnimated:YES completion:nil];
            break;
        }
        case 1: {
            
            self.coverImageView = [[UIImageView alloc] initWithFrame:kScreen_Frame];

            if (isiPhone5) {
                UIImage *cover = [UIImage imageNamed:@"photoDetail_preview_cover"];
                self.coverImageView.image = cover;
            } else {
                UIImage *cover = [UIImage imageNamed:@"photoDetail_preview_cover_4s"];
                self.coverImageView.image = cover;
            }
            
            self.coverImageView.hidden = NO;
            [self.view addSubview:self.coverImageView];
            self.segmentedControl.hidden = YES;

            break;
        }
        case 2: {
            Photo* photo = [self.dataArray objectAtIndex:self.currentItemIndex];
           
            UIImageWriteToSavedPhotosAlbum(photo.largeImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
            break;
        }
        case 3: {
            
            [kApp initShareViewWithUrl:ShareUrl andWithTitle:ShareTitle andWithInfo:NotifyPaperShare andWithImageUlr:ShareImageUrl andIsSuccess:^(BOOL isSuccess) {
                if(isSuccess)
                {
                    [PopTips tips:kApp.rootNav.view Msg:NotifyShareSuccess];
                }
                else{
                    [PopTips tips:kApp.rootNav.view Msg:NotifyShareError];
                }
            }];
            break;
        }
        default:
            break;
    }
    
    self.segmentedControl.selectedSegmentIndex = HMSegmentedControlNoSegment;

}


- (void)image:(UIImage *)image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
     if (error != nil) {
         NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleError
                                                           title:@"保存失败"
                                                         message:NotifyPaperDownError
                                                        delegate:nil];
         [alert show];
    } else {
        NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleSuccess
                                                          title:@"保存成功"
                                                        message:NotifyPaperDownSuccess
                                                       delegate:nil];
        [alert show];
    }
}


// Only work for iOS7
-(BOOL)prefersStatusBarHidden
{
    return YES;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation
{
    return UIStatusBarAnimationNone;
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
